package org.familysearch.fsapi.gwt.samples.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import org.familysearch.fsapi.gwt.common.client.entities.Temple;
import org.familysearch.fsapi.gwt.samples.client.handlers.TempleHandler;
import org.familysearch.fsapi.gwt.samples.client.handlers.TempleListHandler;
import org.familysearch.fsapi.gwt.services.client.TempleServiceProxy;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class TempleListSample extends Composite {

	private static TempleListSample singleton;
    public static TempleListSample get()
    {
        if( singleton == null )
        {
            singleton = new TempleListSample();
        }
        return singleton;
    }
    
    // widgets
    private ScrollPanel scrollPanel;
    private VerticalPanel panel;
    private Button button;
    
    private VerticalPanel templeListVPanel = new VerticalPanel();
    private DialogBox templeListDialogBox = new DialogBox();
    private VerticalPanel templeListDialogVPanel = new VerticalPanel();
    
    
    private VerticalPanel templeDetailVPanel = new VerticalPanel();
    private DialogBox templeDetailDialogBox = new DialogBox();
	private VerticalPanel templeDetailDialogVPanel = new VerticalPanel();
	
	private java.util.Date start;
	private java.util.Date end;

	private boolean hasTempleListData = false;

	private long fetchTimer;

	private long buildPanelsTimer;	
	
	public TempleListSample()
	{
		
		singleton = this;
		
		scrollPanel = new ScrollPanel();
		scrollPanel.add(templeListVPanel);
		scrollPanel.setSize("300px", "200px");
		
		panel = new VerticalPanel();
		
		button = new Button("Get temple list");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (hasTempleListData) {
					showTempleListDialog();
				} else {
					startTimer();
					getTempleList();
				}
			}
		});
		
		panel.add(button);
		
	    // Create the dialog box
	    templeListDialogBox.setAnimationEnabled(false);
	    Button closeButton = new Button("Close");
	    templeListDialogVPanel.setWidth("100%");
	    templeListDialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
	    templeListDialogVPanel.add(scrollPanel);
	    
	    templeListDialogVPanel.add(closeButton);

		closeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				templeListDialogBox.hide();
			}
		});

	    templeListDialogBox.setWidget(templeListDialogVPanel);
	    
	    Anchor refresh = new Anchor();
	    refresh.setText("Reload application");
		refresh.setStyleName("refresh");
		refresh.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				reloadWindow();
			}

		});
		panel.add(refresh);
	    
	    // create the detail dialog box, but don't do anything with it right now
	    templeDetailDialogBox.setAnimationEnabled(false);
	    Button closeButtonTempleDetail = new Button("Close");
	    templeDetailDialogVPanel.setWidth("100%");
	    templeDetailDialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		templeDetailDialogVPanel.add(templeDetailVPanel);
		templeDetailDialogVPanel.add(closeButtonTempleDetail);
		closeButtonTempleDetail.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				templeDetailDialogBox.hide();
			}
		});
		templeDetailDialogBox.setWidget(templeDetailDialogVPanel);

	    
		initWidget(panel);
		
		
	}
	
    protected void startTimer() {
    	start = new Date();
	}
    
    protected void endTimer() {
    	end = new Date();
	}    
    
    protected long timeDelta() {
    	long delta = end.getTime() - start.getTime();
    	//GWT.log("delta=" + delta, null);
    	return delta;
	}      

	public native void reloadWindow()/*-{
    
    var currLocation = $wnd.location.toString();
    $wnd.location.href = currLocation;
}-*/;	


	public void getTempleList()
    {
    	showLoadingTempleList();
    	TempleServiceProxy.get().getTemples(new TempleListHandler());
    }

	
	public void showError(String error)
	{
		GWT.log(error, null);
	}

	public void showTemple(Temple temple) {
		
		endTimer();
		fetchTimer = timeDelta();
		GWT.log("fetch timer=" + fetchTimer, null);
		
		templeDetailVPanel.clear();
		TempleWidgetShort tw = new TempleWidgetShort(temple, false);
		templeDetailVPanel.add(tw);
		showTempleDetailDialog();
		
		
	}
	
	public void showTemples(ArrayList<Temple> temples) {
		
		
		endTimer();
		fetchTimer = timeDelta();
		GWT.log("fetch timer=" + fetchTimer, null);
		
		startTimer();
		templeListVPanel.clear();
		for (Iterator iterator = temples.iterator(); iterator.hasNext();) {
			Temple temple = (Temple) iterator.next();
			TempleWidgetShort tw = new TempleWidgetShort(temple, true);
			templeListVPanel.add(tw);
		}
		endTimer();
		buildPanelsTimer = timeDelta();
		GWT.log("build panels timer=" + buildPanelsTimer, null);
		
		showTempleListDialog();
		finishedLoadingTempleList();
        hasTempleListData  = true;
        
        
        
	}
	
	private void showTempleDetailDialog()
	{
        templeDetailDialogBox.center();
        double secs = Double.parseDouble( Long.toString(fetchTimer));
        double secsExact = secs / 1000;
        templeDetailDialogBox.setText("Temple Detail from the FamilySearch Temple API ("+secsExact+" sec)");
        templeDetailDialogBox.show();
		
	}
	
	private void showTempleListDialog()
	{
        templeListDialogBox.center();
        // conver fetchTimer to seconds / 1000
        double secs = Double.parseDouble( Long.toString(fetchTimer));
        double secsExact = secs / 1000;
        templeListDialogBox.setText("Temple List from the FamilySearch Temple API ("+secsExact+" sec)");
        templeListDialogBox.show();
	}
	
	public void showLoadingTempleList()
	{
		button.setText("Loading...");
		button.setEnabled(false);
	}
	
	public void finishedLoadingTempleList()
	{
		button.setText("Click again.");
		button.setEnabled(true);
	}	
	
	public class TempleWidgetShort extends Composite
	{
		private Temple temple;
		HorizontalPanel h = new HorizontalPanel();
		VerticalPanel v = new VerticalPanel();
		
		public TempleWidgetShort(final Temple temple, boolean isShortForm)
		{
			this.temple = temple;
			HTML c = new HTML("&nbsp;(" + temple.getCode() + ")");
			HTML n = new HTML(temple.getName());
			h.add(n);
			h.add(c);
			
			v.add(h);
			
			if(isShortForm)
			{
				
				h.setStyleName("clickable");

				c.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						loadTemple(temple);
					}
				});

				n.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						loadTemple(temple);
					}
				});		
			}
			else
			{
				// add more data for longform
				HTML l = new HTML(temple.getLocation());
				v.add(l);
				if( temple.getDedicationDate() != null )
				{
					HTML d = new HTML("Dedicated on " + temple.getDedicationDate().toString());
					v.add(d);
				}

			}
			
			initWidget(v);
			
		}

		protected void loadTemple(Temple t) {
			GWT.log("Load " + t.getCode(), null);
			startTimer();
			TempleServiceProxy.get().getTemple(t, new TempleHandler());
		}

	}


}
